/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fileupload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import vehicle.bol.AlbumBol;
import vehicle.entity.Abums;

/**
 *
 * @author caodangtinh
 */
@ManagedBean
@SessionScoped
public class FileUploadControl {

    private static final int BUFFER_SIZE = 6124;
    private String folderToUpload;
    AlbumBol albumBol = new AlbumBol();
    Abums abums;

    /** Creates a new instance of UploadBean */
    public FileUploadControl() {
        abums = new Abums();
    }

    public void handleFileUpload(FileUploadEvent event) {
        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        File result = new File(extContext.getRealPath("//ImgCar//" + event.getFile().getFileName()));
        System.out.println(extContext.getRealPath("//ImgCar//" + event.getFile().getFileName()));

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(result);

            byte[] buffer = new byte[BUFFER_SIZE];

            int bulk;
            InputStream inputStream = event.getFile().getInputstream();
            while (true) {
                bulk = inputStream.read(buffer);
                if (bulk < 0) {
                    break;
                }
                fileOutputStream.write(buffer, 0, bulk);
                fileOutputStream.flush();
            }
            abums.setImgName(event.getFile().getFileName());
            abums.setImgUrl(event.getFile().getFileName());
            String a = params.get("vehicleID");
            abums.setVehiclID(Integer.valueOf(params.get("vehicleID")));
            try {
                albumBol.addVehicleImage(abums);
            } catch (Exception e) {
                e.getMessage();
            }
            fileOutputStream.flush();
            fileOutputStream.close();
            inputStream.close();
            FacesMessage msg =
                    new FacesMessage("Upload Success !");
            FacesContext.getCurrentInstance().addMessage(null, msg);

        } catch (IOException e) {
            FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "The files were not uploaded!", "");
            FacesContext.getCurrentInstance().addMessage(null, error);
        }
    }

    public Abums getAbums() {
        return abums;
    }

    public void setAbums(Abums abums) {
        this.abums = abums;
    }
}
